package com.daigou.admin.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.daigou.dto.AjaxResult;
import com.daigou.dto.ServiceResult;
import com.daigou.model.User;
import com.daigou.service.UserService;
import com.daigou.tools.CacheManagerTool;
import com.daigou.tools.SendMobileMessageUtils;
import com.daigou.tools.ValidateCode;

/**
 * 
 * 类名称：LoginController   
 * 创建人：李志   
 * 创建时间：2018年02月14日  上午12:16:42  
 * 修改人：李志   
 * 修改时间：2018年04月14日 00:35:17   
 * @version    
 *
 */
@Controller
@RequestMapping(value = "/admin")
public class LoginController{
	private static final Logger LOGGER = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private UserService userService;
	
	@Autowired
	private CacheManagerTool cacheManagerTool;

	@RequestMapping(value = "/login",method = RequestMethod.POST)
	@ResponseBody
    public AjaxResult login(@RequestBody User user){
		LOGGER.info("开始登录");
		User userDb = userService.login(user.getLoginName().trim(), user.getPwd().trim());
		if(userDb == null){
			return new AjaxResult(false,"用户名或密码错误!");
		}
		return new AjaxResult(true,"登录成功!",userDb);
    }
	
	@RequestMapping(value = "/login",method = RequestMethod.GET)
    public String toLoginPage(HttpServletRequest request,HttpServletResponse response){
		LOGGER.info("进入登录页面");
		Cookie[] cookies = request.getCookies();
        if (null==cookies) {
        	LOGGER.info("没有cookie");
        } else {
            for(Cookie cookie : cookies){
                //找到同名cookie，就将value设置为null，将存活时间设置为0，再替换掉原cookie，这样就相当于删除了。
                if(cookie.getName().equals("userId")){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
                if(cookie.getName().equals("userToken")){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        return "/admin/app/login";
    }
	
	@RequestMapping(value = "/register",method = RequestMethod.POST)
	@ResponseBody
    public AjaxResult register(@RequestBody User user){
		LOGGER.info("开始注册");
		//0,超级管理员,1，店铺管理员，2，业务经理，3，业务员
		//从此处注册的，类型为1
		user.setType(1);
		//手机端比较难操作，所以需要去空格
		user.setLoginName(user.getLoginName().trim());
		User userDb = userService.selectByLoingName(user.getLoginName());
		if(userDb != null){
			return new AjaxResult(false,"该手机号已经注册!");
		}
		Integer verifyCodeCache = cacheManagerTool.getVerifyCodeCache(CacheManagerTool.MANAGER_REGISTE, user.getLoginName());
		if(verifyCodeCache == null){
			return new AjaxResult(false,"验证码不存在或已过期!");
		}
		//email里传的是验证码，懒得加字段了
		if(!verifyCodeCache.toString().equals(user.getEmail())){
			return new AjaxResult(false,"验证码不正确!");
		}
		user.setEmail(null);
		user.setPwd(user.getPwd().trim());
		ServiceResult serviceResult = userService.register(user);
		//emailSendSeOrvice.sendMailByVelocity(user.getEmail(),user,EmailTypeEnum.REGISTER.getType());
        return new AjaxResult(serviceResult);
    }
	
	@RequestMapping(value = "/register",method = RequestMethod.GET)
    public String toRegisterPage(){
		LOGGER.info("进入注册页面");
        return "/admin/app/register";
    }
	@RequestMapping(value = "/sendVerifyCode/{loginName}",method = RequestMethod.GET)
	@ResponseBody
    public AjaxResult sendVerifyCode(HttpServletRequest request,@PathVariable("loginName")String loginName){
		LOGGER.info("发送验证码");
		if(loginName == null || "".equals(loginName)){
			return new AjaxResult(false,"请输入手机号!");
		}
		loginName = loginName.trim();
		User userDb = userService.selectByLoingName(loginName);
		if(userDb != null){
			return new AjaxResult(false,"该手机号已经注册!");
		}
		int verifyCode = ValidateCode.getSixRandomString();
		String templateParam = "{\"code\":\""+verifyCode+"\"}";
		try{
			SendMobileMessageUtils.sendSms(loginName, SendMobileMessageUtils.TEMP_CODE_MANAGER_REGISTER,templateParam);
			cacheManagerTool.putVerifyCodeCache(CacheManagerTool.MANAGER_REGISTE, loginName, verifyCode);
		}catch(Exception ex){
			ex.printStackTrace();
			return new AjaxResult(false,"验证码发送失败!");
		}
        return new AjaxResult(true,"验证码已发送至您的手机:"+loginName+"!");
    }
	@RequestMapping(value = "/checkVerifyCode/{loginName}/{verifyCode}",method = RequestMethod.GET)
	@ResponseBody
    public AjaxResult checkVerifyCode(HttpServletRequest request,
    		@PathVariable("loginName")String loginName,
    		@PathVariable("verifyCode")String verifyCode){
		LOGGER.info("发送验证码");
		if(loginName == null || "".equals(loginName.trim())){
			return new AjaxResult(false,"请输入手机号!");
		}
		if(verifyCode == null || "".equals(verifyCode)){
			return new AjaxResult(false,"请输入验证码!");
		}
		loginName = loginName.trim();
		verifyCode = verifyCode.trim();
		Integer verifyCodeCache = cacheManagerTool.getVerifyCodeCache(CacheManagerTool.MANAGER_REGISTE, loginName);
		if(verifyCodeCache == null){
			return new AjaxResult(false,"验证码不存在或已过期!");
		}
		if(!verifyCode.equals(verifyCodeCache.toString())){
			return new AjaxResult(false,"验证码不正确!");
		}
        return new AjaxResult(true,"验证码ok!");
    }
}
